extends Control

# 引用
var player: Player
var data_manager: DataManager

# 当前选中的技能
var selected_skill_index: int = -1
var selected_active_skill_index: int = -1

# 战斗模式
var battle_mode: bool = false
var battle_system = null

# 节点引用
@onready var active_skills_container = $MarginContainer/VBoxContainer/Content/ActiveSkills/GridContainer
@onready var all_skills_container = $MarginContainer/VBoxContainer/Content/AllSkills/ScrollContainer/SkillsContainer
@onready var skill_info_name = $MarginContainer/VBoxContainer/Content/SkillInfo/Panel/VBoxContainer/NameLabel
@onready var skill_info_type = $MarginContainer/VBoxContainer/Content/SkillInfo/Panel/VBoxContainer/TypeLabel
@onready var skill_info_description = $MarginContainer/VBoxContainer/Content/SkillInfo/Panel/VBoxContainer/DescriptionLabel
@onready var skill_info_stats = $MarginContainer/VBoxContainer/Content/SkillInfo/Panel/VBoxContainer/StatsContainer
@onready var equip_button = $MarginContainer/VBoxContainer/Content/SkillInfo/Panel/VBoxContainer/ActionButtons/EquipButton
@onready var unequip_button = $MarginContainer/VBoxContainer/Content/SkillInfo/Panel/VBoxContainer/ActionButtons/UnequipButton

# 初始化节点
func _ready() -> void:
	# 等待节点树准备就绪
	await ready
	
	# 检查节点引用是否正确
	if not active_skills_container:
		push_error("已装备技能容器节点未找到")
	
	if not all_skills_container:
		push_error("所有技能容器节点未找到")
	
	if not skill_info_name or not skill_info_type or not skill_info_description or not skill_info_stats:
		push_error("技能信息节点未找到")
	
	# 连接按钮信号
	if equip_button:
		if not equip_button.pressed.is_connected(_on_equip_button_pressed):
			equip_button.pressed.connect(_on_equip_button_pressed)
	else:
		push_error("装备按钮节点未找到")
	
	if unequip_button:
		if not unequip_button.pressed.is_connected(_on_unequip_button_pressed):
			unequip_button.pressed.connect(_on_unequip_button_pressed)
	else:
		push_error("卸下按钮节点未找到")

# 初始化
func initialize(p_player: Player, p_data_manager: DataManager) -> void:
	player = p_player
	data_manager = p_data_manager
	
	# 重置战斗模式
	battle_mode = false
	battle_system = null
	
	# 更新界面
	update_ui()

# 显示界面
func show_ui() -> void:
	visible = true
	
	# 确保获取最新的玩家数据
	if player:
		# 重新检查玩家技能数据
		selected_skill_index = -1
		selected_active_skill_index = -1
		
	# 刷新界面
	update_ui()

# 隐藏界面
func hide_ui() -> void:
	visible = false

# 更新界面
func update_ui() -> void:
	# 检查玩家引用
	if not player:
		push_error("玩家引用未设置")
		return
	
	# 更新已装备技能
	update_active_skills()
	
	# 更新所有技能
	update_all_skills()
	
	# 更新技能信息
	update_skill_info()

# 更新已装备技能
func update_active_skills() -> void:
	# 检查节点引用
	if not active_skills_container:
		push_error("已装备技能容器节点未找到")
		return
	
	# 清空已装备技能
	for child in active_skills_container.get_children():
		child.queue_free()
	
	# 填充已装备技能
	for i in range(player.active_skills.size()):
		var skill = player.active_skills[i]
		
		# 创建技能面板
		var skill_panel = Panel.new()
		skill_panel.custom_minimum_size = Vector2(120, 120)
		
		# 设置面板样式
		var panel_style = StyleBoxFlat.new()
		panel_style.bg_color = Color(0.15, 0.15, 0.15, 0.9)
		panel_style.border_width_left = 2
		panel_style.border_width_top = 2
		panel_style.border_width_right = 2
		panel_style.border_width_bottom = 2
		
		# 根据技能类型设置不同边框颜色
		match skill.skill_type:
			Skill.SkillType.ATTACK:
				panel_style.border_color = Color(0.8, 0.2, 0.2)  # 红色
			Skill.SkillType.HEAL:
				panel_style.border_color = Color(0.2, 0.8, 0.2)  # 绿色
			Skill.SkillType.BUFF:
				panel_style.border_color = Color(0.2, 0.2, 0.8)  # 蓝色
			Skill.SkillType.DEBUFF:
				panel_style.border_color = Color(0.8, 0.2, 0.8)  # 紫色
			Skill.SkillType.SPECIAL:
				panel_style.border_color = Color(0.8, 0.8, 0.2)  # 黄色
			_:
				panel_style.border_color = Color(0.5, 0.5, 0.5)  # 灰色
		
		skill_panel.add_theme_stylebox_override("panel", panel_style)
		
		# 创建垂直布局
		var vbox = VBoxContainer.new()
		vbox.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		vbox.size_flags_vertical = Control.SIZE_EXPAND_FILL
		vbox.custom_minimum_size = Vector2(110, 110)
		skill_panel.add_child(vbox)
		
		# 创建技能名称标签
		var name_label = Label.new()
		name_label.text = skill.skill_name
		name_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
		name_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
		name_label.custom_minimum_size = Vector2(100, 40)
		vbox.add_child(name_label)
		
		# 创建技能类型标签
		var type_label = Label.new()
		match skill.skill_type:
			Skill.SkillType.ATTACK:
				type_label.text = "攻击技能"
				type_label.add_theme_color_override("font_color", Color(0.8, 0.2, 0.2))
			Skill.SkillType.HEAL:
				type_label.text = "治疗技能"
				type_label.add_theme_color_override("font_color", Color(0.2, 0.8, 0.2))
			Skill.SkillType.BUFF:
				type_label.text = "增益技能"
				type_label.add_theme_color_override("font_color", Color(0.2, 0.2, 0.8))
			Skill.SkillType.DEBUFF:
				type_label.text = "减益技能"
				type_label.add_theme_color_override("font_color", Color(0.8, 0.2, 0.8))
			Skill.SkillType.SPECIAL:
				type_label.text = "特殊技能"
				type_label.add_theme_color_override("font_color", Color(0.8, 0.8, 0.2))
			_:
				type_label.text = "未知类型"
		type_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
		vbox.add_child(type_label)
		
		# 创建技能消耗标签
		var cost_label = Label.new()
		cost_label.text = "消耗: %d 真气" % skill.spirit_cost
		cost_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
		vbox.add_child(cost_label)
		
		# 创建技能按钮（透明，覆盖整个面板）
		var skill_button = Button.new()
		skill_button.flat = true
		skill_button.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		skill_button.size_flags_vertical = Control.SIZE_EXPAND_FILL
		skill_button.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
		
		# 连接按钮信号
		skill_button.pressed.connect(_on_active_skill_pressed.bind(i))
		skill_panel.add_child(skill_button)
		
		# 如果是当前选中的技能，高亮显示
		if i == selected_active_skill_index:
			panel_style.bg_color = Color(0.3, 0.3, 0.3, 0.9)
			panel_style.border_width_left = 3
			panel_style.border_width_top = 3
			panel_style.border_width_right = 3
			panel_style.border_width_bottom = 3
			panel_style.border_color = Color(1, 1, 1, 1)
			skill_panel.add_theme_stylebox_override("panel", panel_style)
		
		# 添加到容器
		active_skills_container.add_child(skill_panel)
	
	# 添加空槽位
	for i in range(player.active_skills.size(), player.max_active_skills):
		# 创建空槽位面板
		var empty_panel = Panel.new()
		empty_panel.custom_minimum_size = Vector2(120, 120)
		
		# 设置面板样式
		var panel_style = StyleBoxFlat.new()
		panel_style.bg_color = Color(0.15, 0.15, 0.15, 0.9)
		panel_style.border_width_left = 2
		panel_style.border_width_top = 2
		panel_style.border_width_right = 2
		panel_style.border_width_bottom = 2
		panel_style.border_color = Color(0.5, 0.5, 0.5, 0.8)
		empty_panel.add_theme_stylebox_override("panel", panel_style)
		
		# 创建垂直布局
		var vbox = VBoxContainer.new()
		vbox.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		vbox.size_flags_vertical = Control.SIZE_EXPAND_FILL
		vbox.custom_minimum_size = Vector2(110, 110)
		empty_panel.add_child(vbox)
		
		# 创建空槽位标签
		var empty_label = Label.new()
		empty_label.text = "空槽位"
		empty_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
		empty_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
		empty_label.custom_minimum_size = Vector2(100, 60)
		vbox.add_child(empty_label)
		
		# 创建空槽位按钮
		var empty_button = Button.new()
		empty_button.flat = true
		empty_button.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		empty_button.size_flags_vertical = Control.SIZE_EXPAND_FILL
		empty_button.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
		
		# 连接按钮信号
		empty_button.pressed.connect(_on_empty_slot_pressed.bind(i))
		empty_panel.add_child(empty_button)
		
		# 添加到容器
		active_skills_container.add_child(empty_panel)

# 更新所有技能
func update_all_skills() -> void:
	# 检查节点引用
	if not all_skills_container:
		push_error("所有技能容器节点未找到")
		return
	
	# 清空所有技能
	for child in all_skills_container.get_children():
		child.queue_free()
	
	# 填充所有技能
	for i in range(player.skills.size()):
		var skill = player.skills[i]
		
		# 创建技能面板
		var skill_panel = Panel.new()
		skill_panel.custom_minimum_size = Vector2(0, 60)
		skill_panel.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		
		# 设置面板样式
		var panel_style = StyleBoxFlat.new()
		panel_style.bg_color = Color(0.15, 0.15, 0.15, 0.9)
		panel_style.border_width_left = 2
		panel_style.border_width_top = 2
		panel_style.border_width_right = 2
		panel_style.border_width_bottom = 2
		
		# 根据技能类型设置不同边框颜色
		match skill.skill_type:
			Skill.SkillType.ATTACK:
				panel_style.border_color = Color(0.8, 0.2, 0.2)  # 红色
			Skill.SkillType.HEAL:
				panel_style.border_color = Color(0.2, 0.8, 0.2)  # 绿色
			Skill.SkillType.BUFF:
				panel_style.border_color = Color(0.2, 0.2, 0.8)  # 蓝色
			Skill.SkillType.DEBUFF:
				panel_style.border_color = Color(0.8, 0.2, 0.8)  # 紫色
			Skill.SkillType.SPECIAL:
				panel_style.border_color = Color(0.8, 0.8, 0.2)  # 黄色
			_:
				panel_style.border_color = Color(0.5, 0.5, 0.5)  # 灰色
		
		skill_panel.add_theme_stylebox_override("panel", panel_style)
		
		# 创建水平布局
		var hbox = HBoxContainer.new()
		hbox.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		hbox.size_flags_vertical = Control.SIZE_EXPAND_FILL
		hbox.custom_minimum_size = Vector2(0, 50)
		skill_panel.add_child(hbox)
		
		# 检查是否已装备
		var is_equipped = false
		for active_skill in player.active_skills:
			if active_skill.skill_name == skill.skill_name:
				is_equipped = true
				break
		
		# 创建复选框
		var checkbox = CheckBox.new()
		checkbox.button_pressed = is_equipped
		checkbox.disabled = is_equipped
		checkbox.tooltip_text = "选择此技能作为当前技能"
		hbox.add_child(checkbox)
		
		# 创建技能信息容器
		var info_vbox = VBoxContainer.new()
		info_vbox.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		hbox.add_child(info_vbox)
		
		# 创建技能名称标签
		var name_label = Label.new()
		name_label.text = skill.skill_name
		name_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
		
		# 如果已装备，添加标记
		if is_equipped:
			name_label.text += " (已装备)"
			name_label.add_theme_color_override("font_color", Color(0.2, 0.8, 0.2))
		
		info_vbox.add_child(name_label)
		
		# 创建技能类型和消耗标签
		var type_cost_label = Label.new()
		var type_text = ""
		match skill.skill_type:
			Skill.SkillType.ATTACK:
				type_text = "攻击技能"
			Skill.SkillType.HEAL:
				type_text = "治疗技能"
			Skill.SkillType.BUFF:
				type_text = "增益技能"
			Skill.SkillType.DEBUFF:
				type_text = "减益技能"
			Skill.SkillType.SPECIAL:
				type_text = "特殊技能"
			_:
				type_text = "未知类型"
		
		type_cost_label.text = type_text + " | 消耗: " + str(skill.spirit_cost) + " 真气"
		type_cost_label.add_theme_font_size_override("font_size", 12)
		info_vbox.add_child(type_cost_label)
		
		# 如果是当前选中的技能，高亮显示
		if i == selected_skill_index:
			panel_style.bg_color = Color(0.3, 0.3, 0.3, 0.9)
			panel_style.border_width_left = 3
			panel_style.border_width_top = 3
			panel_style.border_width_right = 3
			panel_style.border_width_bottom = 3
			panel_style.border_color = Color(1, 1, 1, 1)
			skill_panel.add_theme_stylebox_override("panel", panel_style)
		
		# 创建技能按钮（透明，覆盖整个面板）
		var skill_button = Button.new()
		skill_button.flat = true
		skill_button.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		skill_button.size_flags_vertical = Control.SIZE_EXPAND_FILL
		skill_button.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND
		
		# 连接按钮信号
		skill_button.pressed.connect(_on_skill_button_pressed.bind(i))
		skill_panel.add_child(skill_button)
		
		# 连接复选框信号
		checkbox.toggled.connect(_on_skill_checkbox_toggled.bind(i))
		
		# 添加到容器
		all_skills_container.add_child(skill_panel)

# 复选框切换处理函数
func _on_skill_checkbox_toggled(toggled: bool, skill_index: int) -> void:
	# 如果选中，尝试装备技能
	if toggled and skill_index >= 0 and skill_index < player.skills.size():
		# 检查是否已装备
		var is_equipped = false
		for active_skill in player.active_skills:
			if active_skill.skill_name == player.skills[skill_index].skill_name:
				is_equipped = true
				break
		
		# 如果未装备，尝试装备
		if not is_equipped:
			player.equip_skill(skill_index)
			
			# 更新界面
			update_ui()

# 更新技能信息
func update_skill_info() -> void:
	# 检查节点引用
	if not skill_info_name or not skill_info_type or not skill_info_description or not skill_info_stats:
		push_error("技能信息节点未找到")
		return
	
	# 检查按钮引用
	if not equip_button or not unequip_button:
		push_error("技能操作按钮节点未找到")
		return
	
	var skill = null
	var is_active = false
	var active_index = -1
	
	# 获取选中的技能
	if selected_skill_index >= 0 and selected_skill_index < player.skills.size():
		skill = player.skills[selected_skill_index]
		
		# 检查是否已装备为当前技能
		for i in range(player.active_skills.size()):
			if player.active_skills[i].skill_name == skill.skill_name:
				is_active = true
				active_index = i
				break
	elif selected_active_skill_index >= 0 and selected_active_skill_index < player.active_skills.size():
		skill = player.active_skills[selected_active_skill_index]
		is_active = true
		active_index = selected_active_skill_index
	
	# 更新技能信息显示
	if skill:
		skill_info_name.text = skill.skill_name
		skill_info_name.add_theme_color_override("font_color", Color(0.9, 0.9, 0.9))
		
		# 更新技能类型
		var type_text = "类型: "
		var type_color = Color(0.8, 0.8, 0.8)
		match skill.skill_type:
			Skill.SkillType.ATTACK:
				type_text += "攻击技能"
				type_color = Color(0.8, 0.2, 0.2)
			Skill.SkillType.HEAL:
				type_text += "治疗技能"
				type_color = Color(0.2, 0.8, 0.2)
			Skill.SkillType.BUFF:
				type_text += "增益技能"
				type_color = Color(0.2, 0.2, 0.8)
			Skill.SkillType.DEBUFF:
				type_text += "减益技能"
				type_color = Color(0.8, 0.2, 0.8)
			Skill.SkillType.SPECIAL:
				type_text += "特殊技能"
				type_color = Color(0.8, 0.8, 0.2)
		skill_info_type.text = type_text
		skill_info_type.add_theme_color_override("font_color", type_color)
		
		skill_info_description.text = skill.description
		
		# 更新技能属性
		for child in skill_info_stats.get_children():
			child.queue_free()
		
		# 添加技能属性
		var cost_label = Label.new()
		cost_label.text = "真气消耗: %d" % skill.spirit_cost
		cost_label.add_theme_color_override("font_color", Color(0.2, 0.6, 0.8))
		skill_info_stats.add_child(cost_label)
		
		var cooldown_label = Label.new()
		cooldown_label.text = "冷却时间: %d 回合" % skill.cooldown
		cooldown_label.add_theme_color_override("font_color", Color(0.8, 0.6, 0.2))
		skill_info_stats.add_child(cooldown_label)
		
		var power_label = Label.new()
		power_label.text = "基础威力: %d" % skill.base_power
		power_label.add_theme_color_override("font_color", Color(0.8, 0.2, 0.2))
		skill_info_stats.add_child(power_label)
		
		var scaling_label = Label.new()
		scaling_label.text = "缩放属性: %s (x%.1f)" % [skill.scaling_stat, skill.scaling_factor]
		scaling_label.add_theme_color_override("font_color", Color(0.2, 0.8, 0.6))
		skill_info_stats.add_child(scaling_label)
		
		# 添加分隔线
		var separator = HSeparator.new()
		skill_info_stats.add_child(separator)
		
		# 检查是否有元素属性
		if skill.has_meta("element"):
			var element_label = Label.new()
			element_label.text = "元素: %s" % skill.get_meta("element").capitalize()
			element_label.add_theme_color_override("font_color", Color(0.6, 0.6, 0.8))
			skill_info_stats.add_child(element_label)
		
		# 检查是否有状态效果
		if skill.has_meta("status_effect") and skill.has_meta("status_chance"):
			var status_label = Label.new()
			status_label.text = "状态效果: %s (%.0f%% 几率)" % [
				skill.get_meta("status_effect").capitalize(),
				skill.get_meta("status_chance") * 100
			]
			status_label.add_theme_color_override("font_color", Color(0.8, 0.5, 0.8))
			skill_info_stats.add_child(status_label)
		
		# 检查是否有目标类型
		if skill.has_meta("targets"):
			var targets_label = Label.new()
			targets_label.text = "目标: %s" % skill.get_meta("targets").capitalize()
			targets_label.add_theme_color_override("font_color", Color(0.7, 0.7, 0.2))
			skill_info_stats.add_child(targets_label)
		
		# 添加分隔线
		var separator2 = HSeparator.new()
		skill_info_stats.add_child(separator2)
		
		# 添加当前状态信息
		var status_label = Label.new()
		if is_active:
			status_label.text = "当前状态: 已装备"
			status_label.add_theme_color_override("font_color", Color(0.2, 0.8, 0.2))
		else:
			status_label.text = "当前状态: 未装备"
			status_label.add_theme_color_override("font_color", Color(0.8, 0.2, 0.2))
		skill_info_stats.add_child(status_label)
		
		# 更新按钮状态
		equip_button.visible = not is_active
		equip_button.disabled = is_active or player.active_skills.size() >= player.max_active_skills
		unequip_button.visible = is_active
		unequip_button.disabled = not is_active
		
		# 如果装备已满，显示提示
		if not is_active and player.active_skills.size() >= player.max_active_skills:
			var full_label = Label.new()
			full_label.text = "技能栏已满，请先卸下一个技能"
			full_label.add_theme_color_override("font_color", Color(0.8, 0.2, 0.2))
			skill_info_stats.add_child(full_label)
	else:
		# 没有选中技能时显示默认信息
		skill_info_name.text = "未选择技能"
		skill_info_type.text = "类型: 无"
		skill_info_description.text = "请选择一个技能查看详细信息。"
		
		# 清空属性显示
		for child in skill_info_stats.get_children():
			child.queue_free()
		
		# 禁用按钮
		equip_button.visible = false
		unequip_button.visible = false

# 技能按钮点击事件
# 设置战斗模式
func set_battle_mode(is_battle: bool, p_battle_system = null) -> void:
	battle_mode = is_battle
	battle_system = p_battle_system
	
	# 更新界面
	update_ui()

# 技能按钮点击回调
func _on_skill_button_pressed(skill_index: int) -> void:
	# 如果是战斗模式，使用技能并关闭界面
	if battle_mode and battle_system:
		# 使用选中的技能
		battle_system.execute_player_action("skill", skill_index, 0) # 默认攻击第一个敌人
		
		# 隐藏技能界面
		hide_ui()
		
		# 恢复战斗系统
		battle_system.set_paused(false)
		return
	selected_skill_index = skill_index
	selected_active_skill_index = -1
	update_skill_info()

# 已装备技能点击事件
func _on_active_skill_pressed(active_skill_index: int) -> void:
	selected_active_skill_index = active_skill_index
	selected_skill_index = -1
	update_skill_info()

# 空槽位点击事件
func _on_empty_slot_pressed(slot_index: int) -> void:
	# 如果有选中的技能，尝试装备
	if selected_skill_index >= 0 and selected_skill_index < player.skills.size():
		_on_equip_button_pressed()

# 装备按钮点击事件
func _on_equip_button_pressed() -> void:
	if selected_skill_index >= 0 and selected_skill_index < player.skills.size():
		# 装备技能
		player.equip_skill(selected_skill_index)
		
		# 更新界面
		update_ui()

# 卸下按钮点击事件
func _on_unequip_button_pressed() -> void:
	if selected_active_skill_index >= 0 and selected_active_skill_index < player.active_skills.size():
		# 卸下技能
		player.unequip_skill(selected_active_skill_index)
		
		# 更新界面
		selected_active_skill_index = -1
		update_ui()

# 关闭按钮点击事件
func _on_close_button_pressed() -> void:
	hide_ui()
